package me.jeeson.android.komvp.mvp.base

import org.simple.eventbus.EventBus

import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable

/**
 * Created by jess on 16/4/28.
 */
open class BasePresenter<M : IModel, V : IView> : IPresenter {

    protected var mCompositeDisposable: CompositeDisposable? = null

    protected var mModel: M? = null
    protected var mRootView: V? = null

    constructor(model: M, rootView: V) {
        this.mModel = model
        this.mRootView = rootView
        onAttach()
    }

    constructor(rootView: V) {
        this.mRootView = rootView
        onAttach()
    }

    constructor() {
        onAttach()
    }


    override fun onAttach() {
        if (useEventBus()) {
            //如果要使用eventbus请将此方法返回true
            EventBus.getDefault().register(this)//注册EventBus
        }
    }

    override fun onDetach() {
        if (useEventBus()) {
            //如果要使用eventbus请将此方法返回true
            EventBus.getDefault().unregister(this)//解除注册EventBus
        }
        unDispose()//解除订阅
        if (mModel != null)
            mModel!!.onDetach()
        this.mModel = null
        this.mRootView = null
        this.mCompositeDisposable = null
    }

    /**
     * 是否使用eventBus,默认为使用(true)，
     * @return
     */
    protected fun useEventBus(): Boolean {
        return true
    }


    protected fun addDispose(disposable: Disposable) {
        if (mCompositeDisposable == null) {
            mCompositeDisposable = CompositeDisposable()
        }
        mCompositeDisposable!!.add(disposable)//将所有subscription放入,集中处理
    }

     fun unDispose() {
        if (mCompositeDisposable != null) {
            mCompositeDisposable!!.clear()//保证activity结束时取消所有正在执行的订阅
        }
    }
}
